package com.csliubo.eclipse.plugin.sqlgenerator.core.processor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import com.csliubo.eclipse.plugin.sqlgenerator.core.Config;
import com.csliubo.eclipse.plugin.sqlgenerator.core.ConnectionManager;
import com.csliubo.eclipse.plugin.sqlgenerator.core.OuputTypeFactory;
import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Row;
import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Table;

public class SqlProcessor extends Thread {

    private Table               table;
    private String              sql;
    private CountDownLatch      latch;

    public SqlProcessor(Table table, String sql, CountDownLatch latch) {
        this.table = table;
        this.sql = sql;
        this.latch = latch;
    }

    SqlProcessor() {
    }

    public List<Row> process(String sql) throws Throwable {
        Connection con = ConnectionManager.getConnection();
        PreparedStatement pstmt = null;
        pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        List<Row> rows = OuputTypeFactory.getResultSetHandler(Config.getOuputFormat()).convertResultSetToRows(rs);
        pstmt.close();
        con.close();
        return rows;
    }

    public void run() {
        try {
            table.setRows(process(sql));
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            latch.countDown();
        }
    }
}
